package com.tange.ai.core.demo.add.ap;

import android.Manifest;
import android.content.Intent;
import android.graphics.Color;
import android.net.wifi.ScanResult;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.tange.ai.core.demo.R;
import com.tange.ai.core.demo.Utils;
import com.tange.ai.core.demo.databinding.ActivityAddApScanBinding;
import com.tange.ai.core.demo.databinding.ActivityAddTypeChooseBinding;
import com.tange.module.add.ap.DefaultApMatchRule;
import com.tange.module.add.ap.DeviceApScanner;
import com.tg.appcommon.android.TGLog;

import java.util.ArrayList;
import java.util.List;

public class DeviceApScanActivity extends AppCompatActivity {

    private static final String TAG = "DeviceApScanActivity";

    private ActivityAddApScanBinding binding;

    private DeviceApScanner deviceApScanner;

    private ApListAdapter apListAdapter;
    private ApListAdapter wifiListAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = ActivityAddApScanBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());


        apListAdapter = new ApListAdapter(true);
        wifiListAdapter = new ApListAdapter(false);


        binding.wifiList.setAdapter(wifiListAdapter);
        binding.wifiList.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));


        binding.apList.setAdapter(apListAdapter);
        binding.apList.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));

        getSupportActionBar().hide();

        Utils.setStatusBar(this, Color.TRANSPARENT);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(new String[] {Manifest.permission.ACCESS_FINE_LOCATION}, 100);
        }

        binding.startScan.setOnClickListener(view -> startScan());

    }

    private void startScan() {
        if (deviceApScanner == null) {
            deviceApScanner = DeviceApScanner.create(this,
                    new DefaultApMatchRule("AICAM_"), // 使用默认的匹配规则：前缀匹配，此处设置为 AICAM
                    new DeviceApScanner.Callback() {
                        @Override
                        public void onDeviceApRefresh(List<ScanResult> apList) {
                            // 这里获取扫描到的AP
                            if (apList != null && apList.size() > 0) {
                                binding.apEmptyView.setVisibility(View.GONE);
                            }
                            apListAdapter.refreshApList(apList);
                        }

                        @Override
                        public void onWiFiRefresh(List<ScanResult> wifiList) {
                            // 这里获取扫描到的WiFi（除AP）
                            if (wifiList != null && wifiList.size() > 0) {
                                binding.wifiEmptyView.setVisibility(View.GONE);
                            }
                            wifiListAdapter.refreshApList(wifiList);
                        }

                        @Override
                        public void onError(int errorCode) {
                            Log.i(TAG, "[onError]  errorCode = " + errorCode);
                            resetBtn();
                            binding.apEmptyView.setVisibility(View.VISIBLE);
                            binding.apEmptyView.setText("错误： " + errorCode);

                            // DeviceApScanner.ERROR_DEVICE_AP_NOT_FOUND ： 扫描15次后仍无AP
                            // DeviceApScanner.ERROR_PHONE_WIFI_NOT_ENABLED ： 手机WiFi未开启
                            // DeviceApScanner.ERROR_PERMISSION_NOT_GRANTED ： APP未获得定位权限
                        }

                        @Override
                        public void onFinish() {
                            resetBtn();
                        }
                    });

            // 自定义：扫描5次
            deviceApScanner.setMaxScanCount(5);
        }

        deviceApScanner.startScan();

        binding.startScan.setText("扫描中...");
        binding.startScan.setEnabled(false);
        binding.apEmptyView.setVisibility(View.VISIBLE);
        binding.wifiEmptyView.setVisibility(View.VISIBLE);
    }

    private void resetBtn() {
        binding.startScan.setText("重新扫描");
        binding.startScan.setEnabled(true);
        binding.startScan.setOnClickListener(view -> deviceApScanner.restartScan());
    }


    public class ApListAdapter extends RecyclerView.Adapter<ViewHolder> {

        private List<ScanResult> apList = new ArrayList<>();

        private boolean isAp = false;

        public ApListAdapter(boolean isAp) {
            this.isAp = isAp;
        }

        public void refreshApList(List<ScanResult> list) {
            this.apList.clear();
            this.apList.addAll(list);
            notifyDataSetChanged();
        }

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
            View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_scan_ap, viewGroup, false);
            return new ViewHolder(view);
        }

        @Override
        public void onBindViewHolder(ViewHolder viewHolder, final int position) {
            final String apName = apList.get(position).SSID;
            viewHolder.textView.setText(apName);
            if (isAp) {
                viewHolder.itemView.setOnClickListener(view -> {
                    Intent intent = new Intent(view.getContext(), WiFiConfigurationActivity.class);
                    intent.putExtra(WiFiConfigurationActivity.DEVICE_AP_NAME, apName);
                    startActivity(intent);
                    finish();
                });
            }
        }

        @Override
        public int getItemCount() {
            return apList.size();
        }
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {

        public final TextView textView;

        public ViewHolder(View view) {
            super(view);
            textView = view.findViewById(R.id.ap_name);
        }
    }
}